package tpase.client.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import it.unisa.dia.gas.jpbc.Element;
import tpase.client.VO.Message;
import tpase.client.VO.StatusCode;

import java.util.List;
import java.util.Map;

public class ClientLoginToStorageHandler extends ChannelInboundHandlerAdapter {
    private String uid;
    private Element authUidStorage;
    private List<Integer> loginResultList;

    public ClientLoginToStorageHandler(String uid, Element authUidStorage, List<Integer> loginResultList) {
        this.uid = uid;
        this.authUidStorage = authUidStorage;
        this.loginResultList = loginResultList;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Message request = new Message(StatusCode.LOGIN_REQUEST);
        Map<String, byte[]> map = request.getMap();
        map.put("uid", uid.getBytes());
        map.put("auth", authUidStorage.toBytes());

        ctx.writeAndFlush(request);

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message respond = (Message) msg;
        int statusCode = respond.getStatusCode();
        switch (statusCode) {
            case StatusCode.LOGIN_RESPONSE:
                loginResponse(ctx, respond);
                break;
            case StatusCode.LOGIN_NO_UID_RESPONSE:
                loginNoUidResponse(ctx, respond);
                break;
            case StatusCode.LOGIN_PWD_WRONG:
                loginPwdWrong(ctx, respond);
                break;
        }
        ctx.close();

    }

    private void loginPwdWrong(ChannelHandlerContext ctx, Message respond) {
        loginResultList.add(StatusCode.LOGIN_PWD_WRONG);
    }

    private void loginNoUidResponse(ChannelHandlerContext ctx, Message respond) {
        loginResultList.add(StatusCode.LOGIN_NO_UID_RESPONSE);
    }

    private void loginResponse(ChannelHandlerContext ctx, Message respond) {
        loginResultList.add(StatusCode.LOGIN_RESPONSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("ClientLoginToStorageHandler: 发生异常，关闭通道");
        System.out.println(cause.toString());
        ctx.close();
    }
}
